package com.util;

 

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


/*import com.fasterxml.jackson.databind.ObjectMapper;*/

/*import sun.awt.image.PNGImageDecoder;




import com.mchange.v2.c3p0.codegen.JdbcProxyGenerator;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.imageio.plugins.png.PNGImageWriter;*/


public class WebUtil {
	

	// Ĭ��ʹ�õ�ǩ����(δָ��ǩ����ʱ����ֵ��������)
	private static final int csid = 5341;
	public static final String pattern_ymd = "yyyy-MM-dd"; // pattern_ymd
	public static final String pattern_ymd_hms = "yyyy-MM-dd HH:mm:ss"; // pattern_ymdtime
	public static final String pattern_ymd_hms_s = "yyyy-MM-dd HH:mm:ss:SSS"; // pattern_ymdtimeMillisecond
	public static final String pattern_y="yyyy";
	public static final String pattern_ym="yyyy-MM";
	
	public static final String image_path = File.separator + "common" + File.separator + "upload" + File.separator + "images"; 
	
	public static int[] getParms(String ids){
		String[] parms =  ids.split(",");
		int[] idss =new int[parms.length];
		for(int i = 0;i<parms.length;i++){
			idss[0] = Integer.parseInt(parms[0]); 
		}
		return idss;
	}

	public static Map<String,Object> getMap(String[] keys,Object[] values) {
		if (keys != null && values != null && keys.length == values.length) {
			Map<String, Object> map = new HashMap<String, Object>();
			for (int i = 0, len = keys.length; i < len; i++) {
				map.put(keys[i], values[i]);
			}
			return map;
		}
		return null;
	}
	
	
	/**
	 * ��ȡ��ǰʱ��
	 * @return
	 */
	public static Date getDate(){
		return new Date();
	}
	
	public static String date(){
		SimpleDateFormat sdf = new SimpleDateFormat(pattern_ymd);
		return sdf.format(getDate());
	}
	
	/**
	 * ��ʽ��
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String format(Date date, String pattern) {
		DateFormat format = new SimpleDateFormat(pattern);
		return format.format(date);
	}
	
	/**
	 * ��һ���µ�����
	 * @return
	 */
	public static String format(){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH,-1);
		return format(c.getTime(),pattern_ym);
	}
	
	/**
	 * �Ƚϴ���ʱ���뵱ǰʱ��Ƚϲ�����ֵ
	 * @param date
	 * @return
	 */
	public static String format(String date){
		Boolean logic  = lgOrTg(date,format(getDate(), pattern_ym));
		if(logic){
			return date;
		}else{
			return format();
		}
	}
	
	/**
	 * ����һ������ظ���8λ��
	 * @return
	 */
	public static  String  getWashedCode(){
		Long str = (WebUtil.getDate().getTime());
		String time = str.toString();
		String code = time.substring(time.length()-7);
		String washCode = code +(new Random().nextInt(10));
		return washCode;
	}
	
	/**
	 * ��ʱ���ַ�ת��Ϊ16����
	 * @param s
	 * @return
	 */
	  public static String toHexString() {  
	      return  Long.toHexString(getDate().getTime());
	    }  

		
	/**
	 * ɾ����ļ�
	 * Qing W
	 */
	public static boolean deleteFile(String url){
		File file = new File(url);
		 return file.delete();
	}
	/**
	 * �Ƚ�����ʱ��
	 * @param data1
	 * @param date2
	 * @return
	 */
	public static boolean  lgortg(String data1,String date2){
		SimpleDateFormat df = new SimpleDateFormat(pattern_ymd);
	        try {
	            Date dt1 = df.parse(data1);
	            Date dt2 = df.parse(date2);
	            if (dt1.getTime() > dt2.getTime()) {
	                return false;
	            }
	            return true;
	        }catch (Exception e) {
			}
			return false; 
	}
	
	/**
	 * �Ƚ�����ʱ��
	 * @param data1
	 * @param date2
	 * @return
	 */
	public static boolean  lgOrTg(String data1,String date2){
		SimpleDateFormat df = new SimpleDateFormat(pattern_ym);
	        try {
	            Date dt1 = df.parse(data1);
	            Date dt2 = df.parse(date2);
	            if (dt1.getTime() >= dt2.getTime()) {
	                return false;
	            }
	            return true;
	        }catch (Exception e) {
			}
			return false; 
	}
	
	
	/**
	 * ʱ���Ƿ����ָ��ʱ��
	 * @param time
	 * @return
	 */
	public static boolean lgOrTg(String time,Integer result){
		SimpleDateFormat df = new SimpleDateFormat(pattern_ymd_hms);
		try {
			Date createDateTime = df.parse(time);
			Date nowDate = new Date();
			if((nowDate.getTime()-createDateTime.getTime())>result){
				return true;
			}else{
				return false;
			}
		} catch (ParseException e) {
			return false;
		}
	}
	
	//����ת��
	public static Boolean IsDate(String dateTime){
		SimpleDateFormat sdf = new SimpleDateFormat(pattern_ymd);
		try {
			sdf.parse(dateTime);
		} catch (ParseException e) {
			return false;
		}
		return true;
	}
	
	/**
	 * ��ҳ����
	 * Qing W
	 */												
	public static LinkedList<Integer> count(Integer pageCount,Integer index){//  6    1
		LinkedList<Integer> count = new LinkedList<Integer>();
		
		if(pageCount <5){
			for(int i=1;i<=pageCount;i++){
				count.add(i);
			}
		}else if(index+1 < pageCount){
			if(index <= 1){
				count.add(index);
				count.add(index+1);
				count.add(index+2);
				count.add(index+3);
			}else{
				count.add(index-1);
				count.add(index);
				count.add(index+1);
				count.add(index+2);
			}
		}else{
			if(index >= pageCount){
				count.add(index-3);
				count.add(index-2);
				count.add(index-1);
				count.add(index);
			}else{
				count.add(index-2);
				count.add(index-1);
				count.add(index);
				count.add(index+1);
			}
		}
		return count;
	} 
	
	/**
	 * ҳ��
	 * @param pages
	 * @return
	 */
	public static Integer getPage(String pages){
		Integer page=0;
			try{
			page = Integer.parseInt(pages);
			}catch (Exception e) {
				page=1;
			}
		return page;
	}
	
	
	/**
	 * ҳ��
	 * @param pages
	 * @return
	 */
	public static Integer getRows(String rows){
		Integer row=0;
			try{
				row = Integer.parseInt(rows);
			}catch (Exception e) {
				row=20;
			}
		return row;
	}
	

	

	/**
	 * 
	 */
	public static void uploadfiles() {

	}
	


	public static Object pleaseLogin(){
		return WebUtil.getMap(new String[]{"message","success"},new Object[]{"���ȵ�¼",false});
	}
/*	public static String createThum(InputStream file,String allpath,String context,String name){
		BufferedImage img;
		String imgname=new Date().getTime()+name;
		try {
			img = ImageIO.read(file);
	        File destFile = new File(context+"/common/upload/"+imgname);
	        FileOutputStream out = new FileOutputStream(destFile); // ������ļ���   
	        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
	        
	        encoder.encode(img); // JPEG����  
	        out.close();  
	        return allpath+imgname;
		} catch (IOException e) {
			e.printStackTrace();
		}      // ����Image����  
       
		return null;
	}*/
	public static void Copy(String oldPath, String newPath)   
	{   
		try {   
			int bytesum = 0;   
			int byteread = 0;   
			File oldfile = new File(oldPath);   
			if (oldfile.exists()) {   
				InputStream inStream = new FileInputStream(oldPath);   
				FileOutputStream fs = new FileOutputStream(newPath);   
				byte[] buffer = new byte[1444];   
				int length;   
				while ( (byteread = inStream.read(buffer)) != -1) {   
					bytesum += byteread;    
					fs.write(buffer, 0, byteread);   
				}   
				fs.close();
				inStream.close(); 
			}   
		}  

		catch (Exception e) {   
			System.out.println( "error ");   
			e.printStackTrace();   
		}   
	}
	//�����ļ�
	public static String savefile(InputStream file,String allpath,String context,String name){
		String imgname=new Date().getTime()+name;
		try {
	        File destFile = new File(context+"/common/upload/"+imgname);
	        FileOutputStream out = new FileOutputStream(destFile);
	        int len=0;
	        byte buffer[] = new byte[1024];
	        while((len=file.read(buffer))>0){
	               out.write(buffer, 0, len);
	        }  
	        out.close();  
	        return allpath+""+imgname;
		} catch (IOException e) {
			e.printStackTrace();
		}      
       
		return null;
	}
	/**
	 * @return
	 */
	public static String getDateTime() {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern_ymd_hms);
		return sdf.format(getDate());
	}

	
	
	public static String[] backTimeString (String s) {
		String timeString[] = s.split("-");
		System.out.println(timeString[0].trim());
		System.out.println(timeString[1].trim());
		return timeString;
	}
	
	/**
	 * ��ʽ��
	 * @param date
	 * @param parsePattern
	 * @param returnPattern
	 * @return
	 */
	public static String format(String date, String parsePattern, String returnPattern) {
		return format(parse(date, parsePattern), returnPattern);
	}
	
	/**
	 * ����
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static Date parse(String date, String pattern) {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		try {
			return format.parse(date);
		} catch (ParseException e) {
			System.out.println("ToolDateTime.parse�쳣��dateֵ" + date + "��patternֵ" + pattern);
			return null;
		}
	}
	
	/**
	 * 
	 * @param day 
	 * @return
	 */
	public static String anyDay(Integer day){
		Date date = WebUtil.getDate();
		 Calendar calendar = new GregorianCalendar();
		 calendar.setTime(date);
		 calendar.add(Calendar.DATE,day);//�������������һ��.���������,������ǰ�ƶ�
		 date = calendar.getTime(); //���ʱ��������������һ��Ľ��
		 String tomorrow = WebUtil.format(date, WebUtil.pattern_ymd);
		 return tomorrow;
				 
	}
	
	
/*	public static String imgResizeByWidth641_286(InputStream in,String allpath,String context){
		BufferedImage img;
		String imgname=new Date().getTime()+".jpg";
		try {
			img = ImageIO.read(in);
			BufferedImage image = new BufferedImage(641, 286,BufferedImage.TYPE_INT_RGB );
			image.getGraphics().drawImage(img, 0, 0, 641, 286, null); 
			File destFile = new File(context+"/common/adv/upload/"+imgname);  
			FileOutputStream out = new FileOutputStream(destFile);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
			encoder.encode(image); // JPEG����  
		    out.close();  
		    return allpath+imgname;
		}catch (Exception e) {
			return null;
		}
	}*/
/*	public static String imgResizeByWidth(InputStream in,String allpath,String context){
		BufferedImage img;
		String imgname=new Date().getTime()+".jpg";
		try {
			img = ImageIO.read(in);
			Integer width = img.getWidth();    // �õ�Դͼ��  
			Integer height = img.getHeight();
			int h = (int) (height * 641 / width);  
			BufferedImage image = new BufferedImage(641, h,BufferedImage.TYPE_INT_RGB );
			image.getGraphics().drawImage(img, 0, 0, 641, h, null); 
			File destFile = new File(context+"/common/adv/upload/"+imgname);  
			FileOutputStream out = new FileOutputStream(destFile);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
			encoder.encode(image); // JPEG����  
		    out.close();  
		    return allpath+imgname;
		}catch (Exception e) {
			return null;
		}
	}*/
	
	/**
	  * �õ�ĳ��ĳ�µĵ�һ��
	  * @author dandy
	  * @param year
	  * @param month
	  * @return
	  */
	 public static String getFirstDayOfMonth(int year, int month) {
	 
	  Calendar cal = Calendar.getInstance();
	 
	  cal.set(Calendar.YEAR, year);
	 
	  cal.set(Calendar.MONTH, month-1);
	 
	  cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
	 
	 
	  return new SimpleDateFormat(WebUtil.pattern_ymd).format(cal.getTime());
	 }

	 /**
	  * �õ�ĳ��ĳ�µ����һ��
	  * @author dandy
	  * @param year
	  * @param month
	  * @return
	  */
	 public static String getLastDayOfMonth(int year, int month) {
	 
	  Calendar cal = Calendar.getInstance();
	 
	  cal.set(Calendar.YEAR, year);
	 
	  cal.set(Calendar.MONTH, month-1);
	 
	   cal.set(Calendar.DAY_OF_MONTH, 1);
	  int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	  cal.set(Calendar.DAY_OF_MONTH, value);
	 
	  return new SimpleDateFormat(WebUtil.pattern_ymd).format(cal.getTime());
	 
	 }
	 
	 /**
	  * @author dandy
	  * @param year
	  * @return
	  * ��� 2012 �� ÿ�� �� 1��1�� 2��2��
	  */
	 public static String[] getYearAllMonthFirstDays(int year) {
		 String[] days = new String[12];
		 for (int i = 1; i < 13; i++) {
				days[i-1] = WebUtil.getFirstDayOfMonth(year, i);
			}
		 
		 return days;
	 }
	 
	 /**
	  * @author dandy
	  * @param year
	  * @return
	  * ��� 2012�� ÿ�µ� 1��31�� 12��31��
	  */
	 public static String[] getYearAllMonthLasttDays(int year) {
		 String[] days = new String[12];
		 for (int i = 1; i < 13; i++) {
				days[i-1] = WebUtil.getLastDayOfMonth(year, i);
			}
		 
		 return days;
	 }
	 /**
	  * ת��utf-8
	  * @param str1
	  * @return
	  */
	public static String TFUFT8(String  str1){
		String str2 = null;
		try {
			str2 = new String(str1.getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str2;
	} 
    public static String getUTF8XMLString(String xml) {  
    // A StringBuffer Object  
    StringBuffer sb = new StringBuffer();  
    sb.append(xml);  
    String xmString = "";  
    String xmlUTF8="";  
    try {  
    xmString = new String(sb.toString().getBytes("UTF-8"));  
    xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");  
    System.out.println("utf-8 ���룺" + xmlUTF8) ;  
    } catch (UnsupportedEncodingException e) {  
    // TODO Auto-generated catch block  
    e.printStackTrace();  
    }  
    // return to String Formed  
    return xmlUTF8;  
    } 
	 
    public static String FILEDIR = null;
    /**
     * 上传
     * @param request
     * @throws IOException
     */
    public static void upload(HttpServletRequest request) throws IOException{       
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();       
        File file = new File(FILEDIR);
        if (!file.exists()) {
            file.mkdir();
        }
        Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, MultipartFile> entry = it.next();
            MultipartFile mFile = entry.getValue();
            if(mFile.getSize() != 0 && !"".equals(mFile.getName())){
                write(mFile.getInputStream(), new FileOutputStream(initFilePath(mFile.getOriginalFilename())));
            }
        }
    }
    private static String initFilePath(String name) {
        String dir = getFileDir(name) + "";
        File file = new File(FILEDIR + dir);
        if (!file.exists()) {
            file.mkdir();
        }
        Long num = new Date().getTime();
        Double d = Math.random()*num;
        return (file.getPath() + "/" + num + d.longValue() + "_" + name).replaceAll(" ", "-");
    }
    private static int getFileDir(String name) {
        return name.hashCode() & 0xf;
    }
    public static void download(String downloadfFileName, ServletOutputStream out) {
        try {
            FileInputStream in = new FileInputStream(new File(FILEDIR + "/" + downloadfFileName));
            write(in, out);
        } catch (FileNotFoundException e) {
            try {
                FileInputStream in = new FileInputStream(new File(FILEDIR + "/"
                        + new String(downloadfFileName.getBytes("iso-8859-1"),"utf-8")));
                write(in, out);
            } catch (IOException e1) {              
                e1.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
    /**
     * 写入数据
     * @param in
     * @param out
     * @throws IOException
     */
    public static void write(InputStream in, OutputStream out) throws IOException{
        try{
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } finally {
            try {
                in.close();
            }
            catch (IOException ex) {
            }
            try {
                out.close();
            }
            catch (IOException ex) {
            }
        }
    }  
    
    public static void init(HttpServletRequest request) {
        if(WebUtil.FILEDIR == null){
        	WebUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/") + "file/";
        }
    }
    public static Map<String, String> getMap(){
        Map<String, String> map = new HashMap<String, String>();
        File[] files = new File(WebUtil.FILEDIR).listFiles();
        if(files != null){
            for (File file : files) {
                if(file.isDirectory()){
                    File[] files2 = file.listFiles();
                    if(files2 != null){
                        for (File file2 : files2) {
                            String name = file2.getName();
                            map.put(file2.getParentFile().getName() + "/" + name, name.substring(name.lastIndexOf("_")+1));
                        }
                    }
                }
            }
        }
        return map;
    }
}
